<template>
  <v-dialog v-model="dialogVisible" max-width="500">
    <v-card>
      <v-card-title>{{ form.name ? '编辑文件' : '新建文件' }}</v-card-title>
      <v-card-text>
        <v-form ref="formRef" v-model="valid">
          <v-text-field
            v-model="form.name"
            label="文件名"
            :rules="[(v) => !!v || '文件名不能为空']"
            required
          />
          <v-select
            v-model="form.type"
            label="文件类型"
            :items="fileTypes"
            :rules="[(v) => !!v || '请选择文件类型']"
            required
          />
          <v-select
            v-model="form.tags"
            :items="tags"
            item-title="name"
            item-value="id"
            label="标签"
            multiple
            chips
            closable-chips
          ></v-select>
        </v-form>
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn @click="close">取消</v-btn>
        <v-btn @click="submit" color="primary" :disabled="!valid">保存</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { getTags } from '@/api/tags'

const props = defineProps({
  modelValue: Boolean,
  file: Object,
})

const dialogVisible = ref(false)

const emit = defineEmits(['update:modelValue', 'submit'])

const form = reactive({
  name: '',
  type: '',
  tags: [],
})

const valid = ref(false)
const formRef = ref()

const fileTypes = ['docx', 'xlsx', 'pptx']
const tags = ref([])

const fetchTags = async () => {
  try {
    const response = await getTags()
    tags.value = response.data
  } catch (error) {
    console.error('Error fetching tags:', error)
  }
}

const resetForm = () => {
  if (props.file) {
    form.name = props.file.name || ''
    form.type = props.file.type || null
    form.tags = props.file.tags?.map((tag) => tag.name) || []
  } else {
    form.name = ''
    form.type = ''
    form.tags = []
  }
}

const close = () => {
  dialogVisible.value = false
}

const submit = () => {
  formRef.value.validate().then((success) => {
    if (success) {
      emit('submit', { ...form })
      close()
    }
  })
}

watch(
  () => props.modelValue,
  (val) => {
    dialogVisible.value = val

    if (val) {
      fetchTags()
      resetForm()
    }
  },
)

watch(dialogVisible, (val) => {
  emit('update:modelValue', val)
})

onMounted(() => {
  fetchTags()
})
</script>
